﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace _086.JWT封装的使用.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly IOptionsSnapshot<JWTSettings> JWTSettings;

        public TestController(IOptionsSnapshot<JWTSettings> jWTSettings)
        {
            JWTSettings = jWTSettings;
        }

        [HttpPost]
        public ActionResult<string> Login(string userName, string password)
        {
            if (userName == "fzn" && password == "123")
            {
                List<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, "1"));
                claims.Add(new Claim(ClaimTypes.Name, userName));
                // key
                string key = JWTSettings.Value.SecKey;
                // 过期时间 
                DateTime expires = DateTime.Now.AddSeconds(JWTSettings.Value.ExpireSeconds);
                byte[] secBytes = Encoding.UTF8.GetBytes(key);
                var secKey = new SymmetricSecurityKey(secBytes);
                var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
                var tokenDescriptor = new JwtSecurityToken(claims: claims,
                    expires: expires, signingCredentials: credentials);
                // 生成 JWT
                string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
                return jwt;
            }
            else
            {
                return BadRequest("登录失败 用户名密码错误");
            }
        }
    }
}
